package vaccine.appointment.system.common.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vaccine.appointment.system.common.advice.CommonResult;
import vaccine.appointment.system.common.exception.CommonException;
import vaccine.appointment.system.common.exception.GlobalException;
import vaccine.appointment.system.user.exception.UserException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理CommonException
     */
    @ExceptionHandler(CommonException.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResult<Void> handleCommonException(CommonException e) {
        log.error("业务异常: code={}, msg={}", e.getCode(), e.getMsg(), e);
        return CommonResult.error(e.getCode(), e.getMsg());
    }

    /**
     * 处理UserException
     */
    @ExceptionHandler(UserException.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResult<Void> handleUserException(UserException e) {
        log.error("用户异常: code={}, msg={}", e.getCode(), e.getMsg(), e);
        return CommonResult.error(e.getCode(), e.getMsg());
    }

    /**
     * 处理GlobalException
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseStatus(HttpStatus.OK)
    public CommonResult<Void> handleGlobalException(GlobalException e) {
        log.error("全局异常: code={}, msg={}", e.getCode(), e.getMsg(), e);
        return CommonResult.error(e.getCode(), e.getMsg());
    }

    /**
     * 处理参数验证异常（@Valid）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数验证异常", e);
        FieldError fieldError = e.getBindingResult().getFieldError();
        String errorMessage = fieldError != null ? fieldError.getDefaultMessage() : "参数验证失败";
        return CommonResult.error(400, errorMessage);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult<Void> handleBindException(BindException e) {
        log.error("参数绑定异常", e);
        FieldError fieldError = e.getBindingResult().getFieldError();
        String errorMessage = fieldError != null ? fieldError.getDefaultMessage() : "参数绑定失败";
        return CommonResult.error(400, errorMessage);
    }

    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult<Void> handleConstraintViolationException(ConstraintViolationException e) {
        log.error("约束违反异常", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String errorMessage = violations.isEmpty() ? "参数验证失败" : 
            violations.iterator().next().getMessage();
        return CommonResult.error(400, errorMessage);
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        log.error("非法参数异常", e);
        return CommonResult.error(400, e.getMessage() != null ? e.getMessage() : "非法参数");
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public CommonResult<Void> handleNullPointerException(NullPointerException e) {
        log.error("空指针异常", e);
        return CommonResult.error(500, "系统内部错误");
    }

    /**
     * 处理其他未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public CommonResult<Void> handleException(Exception e) {
        log.error("系统异常", e);
        return CommonResult.error(500, "系统内部错误，请联系管理员");
    }
}

